package com.slz.crm.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slz.crm.common.untils.BaseUnit;
import com.slz.crm.common.untils.ForeignKeyDeleteUtil;
import com.slz.crm.pojo.dto.SalesOpportunityDTO;
import com.slz.crm.pojo.dto.SalesOpportunityQueryDTO;
import com.slz.crm.pojo.entity.*;
import com.slz.crm.pojo.vo.SalesOpportunityVO;
import com.slz.crm.server.annotation.Privacy;
import com.slz.crm.server.constant.MessageConstant;
import com.slz.crm.server.mapper.CustomerCompanyMapper;
import com.slz.crm.server.mapper.SalesOpportunityMapper;
import com.slz.crm.server.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.slz.crm.pojo.entity.SalesOpportunityEntity;
import com.slz.crm.server.mapper.CustomerContactMapper;
import com.slz.crm.server.service.SalesOpportunityService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class SalesOpportunityServiceImpl extends ServiceImpl<SalesOpportunityMapper, SalesOpportunityEntity> implements SalesOpportunityService {

    @Autowired
    private SalesOpportunityMapper salesOpportunityMapper;
    @Autowired
    private CustomerContactMapper customerContactMapper;
    @Autowired
    private CustomerCompanyMapper customerCompanyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ForeignKeyDeleteUtil foreignKeyDeleteUtil;


    @Override
    public boolean update(SalesOpportunityDTO salesOpportunityDTO) {
        SalesOpportunityEntity salesOpportunityEntity = new SalesOpportunityEntity();
        BeanUtils.copyProperties(salesOpportunityDTO, salesOpportunityEntity);
        salesOpportunityEntity.setCreatorId(BaseUnit.getCurrentId());
        return updateById(salesOpportunityEntity);
    }

    @Override
    @Transactional
    public boolean delete(Long id) {
        // 收集不符合状态的商机ID
        SalesOpportunityEntity entity = getById(id);
        if (entity.getStage() != 5) {
            String msg = MessageConstant.OPPORTUNITY_MUST_BE_CLOSED
                    + "，不符合的商机ID：" + id;
            throw new RuntimeException(msg);
        }

        foreignKeyDeleteUtil.deleteCascade(SalesOpportunityEntity.class, List.of(id), 0);
        return salesOpportunityMapper.deleteById(id);
    }

    @Override
    @Privacy
    public Page<SalesOpportunityVO> getAllSalesOpportunity(Integer pageNum, Integer pageSize) {
        List<SalesOpportunityVO> salesOpportunityVOs = new ArrayList<>();
        Page<SalesOpportunityEntity> page = new Page<>(pageNum, pageSize);
        Page<SalesOpportunityEntity> pageResult = salesOpportunityMapper.selectPage(
                page,
                new LambdaQueryWrapper<SalesOpportunityEntity>()
                        .orderByDesc(SalesOpportunityEntity::getCreateTime)
        );

        for (SalesOpportunityEntity entity : pageResult.getRecords()) {
            String[] names = getSalesOpportunityNames(entity);
            SalesOpportunityVO salesOpportunityVO = SalesOpportunityVO.fromEntity(entity, names[0], names[1], names[2], names[3], names[4]);
            salesOpportunityVOs.add(salesOpportunityVO);
        }

        Page<SalesOpportunityVO> pageVO = new Page<>(pageNum, pageSize, pageResult.getTotal());
        BeanUtils.copyProperties(pageResult, pageVO);
        pageVO.setRecords(salesOpportunityVOs);
        return pageVO;
    }

    @Override
    @Privacy
    public SalesOpportunityVO create(SalesOpportunityDTO dto) {

        SalesOpportunityEntity entity = new SalesOpportunityEntity();
        BeanUtils.copyProperties(dto, entity);

        //创建人id
        entity.setCreatorId(BaseUnit.getCurrentId());

        baseMapper.insert(entity);
        String[] names = getSalesOpportunityNames(entity);
        return SalesOpportunityVO.fromEntity(entity, names[0], names[1], names[2], names[3], names[4]);
    }

    /**
     * 获取销售机会相关的所有名称：公司名称、联系人名称、负责人姓名、创建人姓名和审批人姓名
     * @param entity 销售机会实体
     * @return 包含所有名称的数组，顺序为：[companyName, contactName, ownerName, creatorName, approverName]
     */
    private String[] getSalesOpportunityNames(SalesOpportunityEntity entity) {
        String companyName = null;
        String contactName = null;
        String ownerName = null;
        String creatorName = null;
        String approverName = null;

        // 公司名称
        if (entity.getCompanyId() != null) {
            CustomerCompanyEntity companyEntity = customerCompanyMapper.selectById(entity.getCompanyId());
            if (companyEntity != null) {
                companyName = companyEntity.getCompanyName();
            }
        }

        // 联系人名称
        if (entity.getContactId() != null) {
            CustomerContactEntity contactEntity = customerContactMapper.selectById(entity.getContactId());
            if (contactEntity != null) {
                contactName = contactEntity.getName();
            }
        }

        // 负责人名称
        if (entity.getOwnerId() != null) {
            UserEntity userEntity = userMapper.selectById(entity.getOwnerId());
            if (userEntity != null) {
                ownerName = userEntity.getRealName();
            }
        }

        // 创建人名称
        if (entity.getCreatorId() != null) {
            UserEntity userEntity = userMapper.selectById(entity.getCreatorId());
            if (userEntity != null) {
                creatorName = userEntity.getRealName();
            }
        }

        // 审批人名称
        if (entity.getApproverId() != null) {
            UserEntity userEntity = userMapper.selectById(entity.getApproverId());
            if (userEntity != null) {
                approverName = userEntity.getRealName();
            }
        }

        return new String[]{companyName, contactName, ownerName, creatorName, approverName};
    }

    /**
     * 销售机会名称、联系人名称、公司名称、负责人名称、审批人名称、创建人名称
     * @param vo
     */
    private void getName(SalesOpportunityVO vo) {
        //联系人名称
        if (vo.getContactId() != null) {
            CustomerContactEntity contactEntity = customerContactMapper.selectById(vo.getContactId());
            if (contactEntity != null) {
                vo.setContactName(contactEntity.getName());
            }
        }
        //公司名称
        if (vo.getCompanyId() != null) {
            CustomerCompanyEntity companyEntity = customerCompanyMapper.selectById(vo.getCompanyId());
            if (companyEntity != null) {
                vo.setCompanyName(companyEntity.getCompanyName());
            }
        }
        //负责人名称
        if (vo.getOwnerId() != null) {
            UserEntity userEntity = userMapper.selectById(vo.getOwnerId());
            if (userEntity != null) {
                vo.setOwnerName(userEntity.getRealName());
            }
        }
        //审批人名称
        if (vo.getApproverId() != null) {
            UserEntity userEntity = userMapper.selectById(vo.getApproverId());
            if (userEntity != null) {
                vo.setApproverName(userEntity.getRealName());
            }
        }
        //创建人名称
        if (vo.getCreatorId() != null) {
            UserEntity userEntity = userMapper.selectById(vo.getCreatorId());
            if (userEntity != null) {
                vo.setCreatorName(userEntity.getRealName());
            }
        }
        //负责人名称
        if (vo.getOwnerId() != null) {
            UserEntity userEntity = userMapper.selectById(vo.getOwnerId());
            if (userEntity != null) {
                vo.setOwnerName(userEntity.getRealName());
            }
        }
    }

    @Override
    @Privacy
    public Page<SalesOpportunityVO> getSalesOpportunityByQuery(SalesOpportunityQueryDTO queryDTO, Integer pageNum, Integer pageSize) {
        Page<SalesOpportunityEntity> page = new Page<>(pageNum, pageSize);
        Page<SalesOpportunityEntity> pageResult = salesOpportunityMapper.selectPage(
                page,
                getQueryWrapper(queryDTO)
        );
        List<SalesOpportunityVO> salesOpportunityVOs = new ArrayList<>();
        for (SalesOpportunityEntity entity : pageResult.getRecords()) {
            String[] names = getSalesOpportunityNames(entity);
            SalesOpportunityVO salesOpportunityVO = SalesOpportunityVO.fromEntity(entity, names[0], names[1], names[2], names[3], names[4]);
            salesOpportunityVOs.add(salesOpportunityVO);
        }

        Page<SalesOpportunityVO> ansPage = new Page<>();
        BeanUtils.copyProperties(pageResult, ansPage);
        ansPage.setRecords(salesOpportunityVOs);
        return ansPage;
    }

    /**
     * 构造自定义销售机会查询条件
     * @param queryDTO 查询条件DTO
     * @return 查询条件
     */
    public LambdaQueryWrapper<SalesOpportunityEntity> getQueryWrapper(SalesOpportunityQueryDTO queryDTO){
        LambdaQueryWrapper<SalesOpportunityEntity> queryWrapper = new LambdaQueryWrapper<>();

        //销售机会名称模糊搜索
        if(queryDTO.getOpportunityName() != null && !queryDTO.getOpportunityName().isEmpty()){
            queryWrapper.like(SalesOpportunityEntity::getOpportunityName,queryDTO.getOpportunityName());
        }
        //公司名称模糊搜索
        if(queryDTO.getCompanyName() != null && !queryDTO.getCompanyName().isEmpty()){
            Set<Long> companyIds = customerCompanyMapper.selectCompanyIdsByName(queryDTO.getCompanyName());
            if(!companyIds.isEmpty()){
                queryWrapper.in(SalesOpportunityEntity::getCompanyId,companyIds);
            }else{
                queryWrapper.eq(SalesOpportunityEntity::getCompanyId,-1);
            }
        }
        //联系人名称模糊搜索
        if(queryDTO.getContactName() != null && !queryDTO.getContactName().isEmpty()){
            Set<Long> contactIds = customerContactMapper.selectContactIdsByName(queryDTO.getContactName());
            if(!contactIds.isEmpty()){
                queryWrapper.in(SalesOpportunityEntity::getContactId,contactIds);
            }else{
                queryWrapper.eq(SalesOpportunityEntity::getContactId,-1);
            }
        }
        //负责人名称模糊搜索
        if(queryDTO.getOwnerName() != null && !queryDTO.getOwnerName().isEmpty()){
            Set<Long> ownerIds = userMapper.selectUserIdsByUserName(queryDTO.getOwnerName());
            if(!ownerIds.isEmpty()){
                queryWrapper.in(SalesOpportunityEntity::getOwnerId,ownerIds);
            }else{
                queryWrapper.eq(SalesOpportunityEntity::getOwnerId,-1);
            }
        }
        //审批人名称模糊搜索
        if(queryDTO.getApproverName() != null && !queryDTO.getApproverName().isEmpty()){
            Set<Long> approverIds = userMapper.selectUserIdsByUserName(queryDTO.getApproverName());
            if(!approverIds.isEmpty()){
                queryWrapper.in(SalesOpportunityEntity::getApproverId,approverIds);
            }else{
                queryWrapper.eq(SalesOpportunityEntity::getApproverId,-1);
            }
        }
        //创建人名称模糊搜索
        if(queryDTO.getCreatorName() != null && !queryDTO.getCreatorName().isEmpty()){
            Set<Long> creatorIds = userMapper.selectUserIdsByUserName(queryDTO.getCreatorName());
            if(!creatorIds.isEmpty()){
                queryWrapper.in(SalesOpportunityEntity::getCreatorId,creatorIds);
            }else{
                queryWrapper.eq(SalesOpportunityEntity::getCreatorId,-1);
            }
        }
        //销售机会阶段搜索
        if(queryDTO.getStage() != null){
            if(queryDTO.getStage() >= 0 && queryDTO.getStage() <= 5){
                queryWrapper.eq(SalesOpportunityEntity::getStage,queryDTO.getStage());
            }else{
                queryWrapper.eq(SalesOpportunityEntity::getStage,-1);
            }
        }
        //销售机会描述模糊搜索
        if(queryDTO.getDescription() != null && !queryDTO.getDescription().isEmpty()){
            queryWrapper.like(SalesOpportunityEntity::getDescription,queryDTO.getDescription());
        }
        //来源模糊搜索
        if(queryDTO.getSource() != null && !queryDTO.getSource().isEmpty()){
            queryWrapper.like(SalesOpportunityEntity::getSource,queryDTO.getSource());
        }
        //金额范围搜索
        if(queryDTO.getMinAmount() != null && queryDTO.getMaxAmount() != null){
            queryWrapper.between(SalesOpportunityEntity::getAmount,queryDTO.getMinAmount(),queryDTO.getMaxAmount());
        }
        //创建时间范围搜索
        if(queryDTO.getMinCreateTime() != null && queryDTO.getMaxCreateTime() != null){
            queryWrapper.between(SalesOpportunityEntity::getCreateTime,queryDTO.getMinCreateTime(),queryDTO.getMaxCreateTime());
        }
        //关闭日期范围搜索
        if(queryDTO.getMinExpectedCloseDate() != null && queryDTO.getMaxExpectedCloseDate() != null){
            queryWrapper.between(SalesOpportunityEntity::getExpectedCloseDate,queryDTO.getMinExpectedCloseDate(),queryDTO.getMaxExpectedCloseDate());
        }
        //负责人用户ID精确匹配
        if(queryDTO.getOwnerId() != null){
            queryWrapper.eq(SalesOpportunityEntity::getOwnerId,queryDTO.getOwnerId());
        }
        //负责人用户名模糊搜索
        if(queryDTO.getOwnerUserName() != null && !queryDTO.getOwnerUserName().isEmpty()){
            Set<Long> ownerUserIds = userMapper.selectUserIdsByUserName(queryDTO.getOwnerUserName());
            if(!ownerUserIds.isEmpty()){
                queryWrapper.in(SalesOpportunityEntity::getOwnerId,ownerUserIds);
            }else{
                queryWrapper.eq(SalesOpportunityEntity::getOwnerId,-1);
            }
        }
        return queryWrapper;
    }

    @Override
    public void cascadeDeleteByCompanyId(Long companyId) {
        LambdaUpdateWrapper<SalesOpportunityEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SalesOpportunityEntity::getCompanyId, companyId)
               .eq(SalesOpportunityEntity::getIsDeleted, (byte)0)
               .set(SalesOpportunityEntity::getIsDeleted, (byte)5);
        update(wrapper);
    }

    @Override
    public void cascadeDeleteByContactIds(List<Long> contactIds) {
        if (contactIds == null || contactIds.isEmpty()) {
            return;
        }
        LambdaUpdateWrapper<SalesOpportunityEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(SalesOpportunityEntity::getContactId, contactIds)
               .eq(SalesOpportunityEntity::getIsDeleted, (byte)0)
               .set(SalesOpportunityEntity::getIsDeleted, (byte)5);
        update(wrapper);
    }
}
